#include <string>
#include <cstdlib>
#include "playlist.h"
#include "player.h"
#include "decoder.h"
#include "graphics.h"

extern Graphics graphics;

// ----------------
Playlist::Playlist()
// ----------------
{
	selected = 0;
	current = 0;
}

// ----------------
void Playlist::add(std::string filepath)
// ----------------
{
	Decoder* decoder = DecoderFactory::getDecoderByFile(filepath);
	fileInfo info = decoder->getInfo();
	
	if ( info.type.compare("NULL") != 0 && info.type.size() > 0) {
		info.filepath = filepath;
		list.push_back(info);
		if (selected == 0) selected = 1;
		if (current == 0) current = 1;
	}
}

// ----------------
void Playlist::remove(uint32_t entry)
// ----------------
{
	if (entry == 0 || entry > list.size()) return;

	std::vector<fileInfo>::iterator i = list.begin();
	for (uint32_t k=1; k<entry; ++k)
	{
		++i;
	}
	list.erase(i);
	if (list.empty())
	{
		selected = 0;
		current = 0;
	}
}

// ----------------
void Playlist::clear()
// ----------------
{
	list.clear();
	selected = 0;
	current = 0;
}

// ----------------
void Playlist::next()
// ----------------
{
	if (current < list.size() && !list.empty()) ++current;
}

// ----------------
void Playlist::prev()
// ----------------
{
	if (current > 1) --current;
}

/*
// ----------------
void Playlist::moveBlockUp(uint32_t first, uint32_t last)
// ----------------
{
	if (first > 0 && last < entries) {
		fileInfo tmp = list[first-1];
		for (uint32_t i=first; i<=last; ++i) {
			list[i-1] = list[i];
		}
		list[last] = tmp;
	}
}

// ----------------
void Playlist::moveBlockDown(uint32_t first, uint32_t last)
// ----------------
{
	if (first < entries && last < (entries-1)) {
		fileInfo tmp = list[last+1];
		for (uint32_t i=last; i>=first; --i) {
			list[i+1] = list[i];
		}
		list[first] = tmp;
	}
}
*/

// ----------------
fileInfo Playlist::getInfo(uint32_t entry)
// ----------------
{
	return list[entry-1];
}

// ----------------
void Playlist::setCurrent(uint32_t no)
// ----------------
{
	if (no > 0 && no <= list.size()) {
		current = no;
	}
}

// ----------------
uint32_t Playlist::getCurNo()
// ----------------
{
	return current;
}

// ----------------
uint32_t Playlist::numberOfEntries()
// ----------------
{
	return list.size();
}

// ----------------
void Playlist::selEntry(uint32_t no)
// ----------------
{
	if (no > 0 && no <= list.size())
	{
		selected = no;
	}
}

// ----------------
uint32_t Playlist::getSelEntry()
// ----------------
{
	return selected;
}

// ---------------------------------------------------------------------------
void Playlist::redraw()
// ---------------------------------------------------------------------------
{
	selected = current;
	#ifndef DEBUG
	graphics.setBrowserLines(selected-1, &list);
	#endif
}
